package cn.snsprj.authclient.interceptor;

import cn.snsprj.authclient.common.ConstCode;
import cn.snsprj.authclient.common.SessionManage;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.snsprj.authclient.common.ServerResponse;
import cn.snsprj.authclient.util.HttpUtil;
import cn.snsprj.authclient.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author SKH
 * @date 2018-08-21 10:24
 **/
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Value("${cas.server.url}")
    private String authServerUrl;

    @Value("${local.url.index}")
    private String indexUrl;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {

        // 通知serverlogout
        String authServerURLLogout = authServerUrl + "/logout";

        // 验证server的cookie中的server_ticket
        String authServerURLAuth = authServerUrl + "/auth";

        String authServerURLverify = authServerUrl + "/verify_st";

        String requestURI = request.getRequestURI();
        logger.info("====>request uri is {}", requestURI);

        String sourceUrl = this.getRequestURL(request);
        logger.info("====>request url is {}", sourceUrl);

        // 去除第一个斜杠
        requestURI = StringUtils.substringAfter(requestURI, "/");

        // 判断是否为请求静态资源
        Set<String> resourceSuffixSet = new HashSet<>();
        resourceSuffixSet.add("ico");
        resourceSuffixSet.add("xml");
        resourceSuffixSet.add("json");
        resourceSuffixSet.add("xlsx");
        resourceSuffixSet.add("js");
        resourceSuffixSet.add("html");
        resourceSuffixSet.add("css");

        String suffix = StringUtils.substringAfterLast(requestURI, ".");
        if (resourceSuffixSet.contains(suffix)) {
            logger.info("====>suffix is {}", suffix);
            return true;
        }

        String prefix = StringUtils.substringBefore(requestURI, "/");
        logger.info("====>prefix is {}", prefix);

        // 列外的url
        Set<String> exceptURLSet = new HashSet<>();
        exceptURLSet.add("login");
        exceptURLSet.add("logout");
        exceptURLSet.add("index");
        exceptURLSet.add("error");
        exceptURLSet.add("notified_logout");
        exceptURLSet.add("test");

        if (exceptURLSet.contains(prefix)) {
            // 无需拦截的url

            if (StringUtils.equals(prefix, "logout")) {
                // 重定向到authServer的logout接口
                String encodeIndexUrl = URLEncoder.encode(indexUrl, "utf-8");

                String logoutUrl = authServerURLLogout + "?" + ConstCode.SOURCE_URL
                        + "=" + encodeIndexUrl;

                response.sendRedirect(logoutUrl);
            }
            return true;
        } else {

            // 是否可以通过认证
            boolean isAuth;

            // 1、查看请求是否带有ticket
            // 获取server ticket
            String serverTicket = request.getParameter(ConstCode.SERVICE_TICKET);
            logger.info("====>serverTicket is {}", serverTicket);

            if (StringUtils.isBlank(serverTicket)){

                //  请求不带有ticket，session请求
                HttpSession session = request.getSession(false);
                if (session != null) {

                    String sessionTicket = (String) session.getAttribute(ConstCode.SERVICE_TICKET);
                    if (StringUtils.isNotBlank(sessionTicket)){
                        isAuth = true;
                    }else {
                        isAuth = false;
                    }

                }else {
                    // 请求不带ticket并且session为null
                    isAuth = false;
                }

            } else {
                // verify serverTicket
                Map<String, Object> params = new HashMap<>(1);
                params.put("service_ticket", serverTicket);
                String result = HttpUtil.doGet(authServerURLverify, params);
                logger.info("====>request, url is {}, parms is {}, result is {}",
                        authServerURLverify, JsonUtil.obj2String(params), result);

                ServerResponse resultMap = JsonUtil
                        .string2Obj(result, new TypeReference<ServerResponse>() {
                        });

                if (resultMap != null && "200".equals(resultMap.getCode())) {

                    // verify success, create session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(ConstCode.SERVICE_TICKET, serverTicket);
                    SessionManage.MANAGED_SESSIONS.put(serverTicket,session);

                    isAuth = true;
                } else {
                    isAuth = false;
                }

            }

            if (!isAuth){
                // 认证失败，重定向到authServer登录页面，并加上sourceUrl
                String encodeSourceUrl = URLEncoder.encode(sourceUrl, "utf-8");
                String stcAuthUrl = authServerURLAuth + "?" + ConstCode.SOURCE_URL
                        + "=" + encodeSourceUrl;

                logger.info("====>authServerUrl is {}", stcAuthUrl);

                response.sendRedirect(stcAuthUrl);

                return false;
            }else {
                return true;
            }
        }
    }

    private String getRequestURL(HttpServletRequest request) {

        String url = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort()
                + request.getServletPath();

        if (request.getQueryString() != null) {

            url += "?" + request.getQueryString();
        }

        return url;
    }
}
